<template>
    <!-- 按钮 -->
    <el-button :disabled="!category3Id" type="primary" @click="emit('setState', 1)">添加SPU</el-button>

    <!-- spu分页表格 -->
    <el-table :data="tableData" border stripe :style="{ marginTop: '40px', marginBottom: '40px' }">
        <el-table-column type="index" width="100" align="center" label="序号" />
        <el-table-column label="SPU名称" prop="spuName"></el-table-column>
        <el-table-column label="SPU描述" prop="description"></el-table-column>
        <el-table-column label="操作">
            <template v-slot="{ row, $index }">
                <el-button type="primary" icon="ele-Plus" @click="emit('setState' , 2 , row)" title="添加SKU"></el-button>
                <el-button type="primary" icon="ele-Edit" @click="emit('setState', 1, row)" title="编辑SPU"></el-button>
                <el-button type="info" icon="ele-Warning" @click="" title="查看SKU"></el-button>
                <el-button type="danger" icon="ele-Delete" @click="deleteSpu(row.id)" title="删除SPU"></el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 页码 -->
    <el-pagination v-model:current-page="page" v-model:page-size="limit" :pager-count="7" :total="total"
        :page-sizes="[3, 5, 7, 10]" layout="prev, pager, next , sizes, total"></el-pagination>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { storeToRefs } from "pinia";
import { ElMessage } from "element-plus";

export default defineComponent({
    name: "SupList",
});
</script>

<script setup lang="ts">
import { ref, watch } from "vue"
import { requestDeleteSpu, requestSpuPage, type supInfoType } from "@/api/spu"
import useAttrStore from "@/stores/attr";

const attrStore = useAttrStore()
const { category3Id } = storeToRefs(attrStore)

//定义页码数据
const page = ref(1)
const limit = ref(10)
const total = ref(0)
//定义spu分页表格数据
const tableData = ref<supInfoType[]>([])

//封装函数请求spu分页列表
const getSpuPageList = async () => {
    try {
        const result = await requestSpuPage(page.value, limit.value, category3Id.value as number)
        tableData.value = result.records
        total.value = result.total
    } catch (error) {
        ElMessage.error("初始化请求spu分页列表失败!")
    }
}
//1.监听category3Id请求spu分页列表
watch(category3Id, () => {
    //判断3Id为null
    if (category3Id.value === null) {
        tableData.value = []
        total.value = 0
        return
    }
    //发送请求
    getSpuPageList()
}, { immediate: true })

//2.接收自定义事件，向父组件传值
const emit = defineEmits<{
    (event: 'setState', state: number, row?: supInfoType): void
}>()

//3.检测页码改变请求分页列表
watch([page, limit], () => {
    if (category3Id.value === null) return

    getSpuPageList()
})

//4.删除spu的回调
const deleteSpu = async (id: number) => {
    try {
        //删除请求
        await requestDeleteSpu(id)
        //重新请求分页列表
        getSpuPageList()
        //成功提示
        ElMessage.success("删除spu成功!")
    } catch {
        //失败提示
        ElMessage.error("删除spu失败!")
    }
}


</script>